﻿#
#  Usage: add reverse dns record
#  Issue: 2024-02-29
# Author: Leon Hsia
#   Mail: waxwork3@163.com
#

#region 关键代码：强迫以管理员权限运行
if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) { Start-Process powershell.exe "-NoProfile -ExecutionPolicy Bypass -File `"$PSCommandPath`"" -Verb RunAs; exit }
#endregion

$base_path = Split-Path -Path $MyInvocation.MyCommand.Definition
Set-Location $base_path

# 导入DNSServer模块
# Import-Module DNSServer

# 读取TXT文件
$file = "domain_ip.txt"
if (-not (Test-Path -Path $file)) {
    Write-Output "The file $file does not exist."
    Exit
}
$entries = Get-Content -Path $file

# 遍历TXT文件中的条目
$regex = [System.Text.RegularExpressions.Regex]::new("is")
foreach ($entry in $entries) {
    # 分割IP地址和域名
    $parts = $entry.Split(" ")
    $ipaddress = $parts[1]
    $domainname = $parts[0]

    # IP格式检查
    try {
        $ipObject = [System.Net.IPAddress]::Parse($ipaddress)
    }
    catch {
        Write-Host "IP格式错误：$ipaddress"
        Exit
    }
    
    # 域名格式检查
    $regex = [System.Text.RegularExpressions.Regex]::new('([0-9a-z\-]+\.)+[0-9a-z\-]+')
    if ($domainname -notmatch $regex) {
        Write-Host "域名格式错误：$domainname"
        Exit
    }

    # 添加或更新域名
    # $hostName = $null
    # $hostName = [System.Net.Dns]::GetHostEntry($ipObject.IPAddressToString).HostName
    $ipPrefix = ($ipObject.IPAddressToString -split "\.")[0..2]
    # if ($null -eq $hostName) {
    #     Remove-DnsServerResourceRecord -ZoneName ("{0}.in-addr.arpa" -f ($ipPrefix -join ".")) -Name ($ipObject.IPAddressToString -split "\.")[3] -RRType Ptr -Force
    # }
    [array]::Reverse($ipPrefix)
    if (-not (Get-DnsServerZone | Where-Object { $_.IsReverseLookupZone -eq $true }).ZoneName.Contains("{0}.in-addr.arpa" -f ($ipPrefix -join "."))) {
        Add-DnsServerPrimaryZone -ReplicationScope Domain -NetworkId ("{0}.{1}.{2}.0/24" -f $ipPrefix[2], $ipPrefix[1], $ipPrefix[0])
    }
    Remove-DnsServerResourceRecord -ZoneName ("{0}.in-addr.arpa" -f ($ipPrefix -join ".")) -Name ($ipObject.IPAddressToString -split "\.")[3] -RRType Ptr -Force
    Add-DnsServerResourceRecordPtr -Name ($ipObject.IPAddressToString -split "\.")[3] -ZoneName ("{0}.in-addr.arpa" -f ($ipPrefix -join ".")) -PtrDomainName $domainname
}
